package com.jsbj.oauth2.service;

import com.jsbj.user.entities.SysTenantPermission;
import com.jsbj.user.entities.SysUser;
import com.jsbj.user.service.ISysTenantPermissionService;
import com.jsbj.user.service.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

//    @Autowired
//    private IFeignSystemController feignSystemController;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysTenantPermissionService sysTenantPermissionService;

    @Override
    public UserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException {
        // 1. 判断用户名是否为空
        if(StringUtils.isEmpty(loginId)) {
            throw new BadCredentialsException("登录账号不能为空");
        }
        // 2. 通过用户名查询数据库中的用户信息
//        SysUser sysUser = feignSystemController.findUserByUsername(username);
        SysUser sysUser = sysUserService.queryByLoginId(loginId);
        if(sysUser == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        // 3. 通过用户id去查询数据库的拥有的权限信息
//        List<SysMenu> menuList =
//                feignSystemController.findMenuListByUserId(sysUser.getId());
        List<SysTenantPermission> menuList = new ArrayList<>();


        // 4. 封装权限信息（权限标识符code）
        List<GrantedAuthority> authorities = null;
        if(CollectionUtils.isNotEmpty(menuList)) {
            authorities = new ArrayList<>();
            for(SysTenantPermission menu: menuList) {
                // 权限标识
                String code = menu.getMenuCode();
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }

        // 5. 构建UserDetails接口的实现类JwtUser对象
        JwtUser jwtUser = new JwtUser( sysUser.getId(), sysUser.getLoginId(), sysUser.getPassword(),
                sysUser.getUserName(), sysUser.getImageUrl(), sysUser.getMobile(), sysUser.getEmail(),
                1,1,1,sysUser.getDisabled(),authorities );

        return jwtUser;
    }
}
